package com.ruoyi.api.user;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.user.requestVo.HomeDataRequestVo;
import com.ruoyi.api.user.requestVo.HomeDataResponseVo;
import com.ruoyi.api.user.requestVo.MachineBindRequestVo;
import com.ruoyi.api.user.requestVo.MachineSOSRequestVo;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.user.domain.Battery;
import com.ruoyi.user.domain.Health;
import com.ruoyi.user.domain.Location;
import com.ruoyi.user.domain.Machine;
import com.ruoyi.user.domain.Sos;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IBatteryService;
import com.ruoyi.user.service.IHealthService;
import com.ruoyi.user.service.ILocationService;
import com.ruoyi.user.service.IMachineService;
import com.ruoyi.user.service.ISosService;
import com.ruoyi.user.service.IStepService;

import io.swagger.annotations.ApiOperation;

/**
 * 问题反馈 信息操作处理
 * 
 * @author ruoyi
 * @date 2018-12-23
 */
@Controller
@RequestMapping("/api/home")
public class ApiHomeController extends BaseController
{
    private String prefix = "home";
	
	@Autowired
	private IHealthService healthService;
	@Autowired
	private IStepService stepService;
	@Autowired
	private IMachineService machineService;
	@Autowired
	private ILocationService locationService;
	@Autowired
	private ISosService sosService;
	@Autowired
    private IBatteryService batteryService;
	
	/**
	 * 首页获取设备数据
	 */
	@PostMapping("/data")
	@ResponseBody
	@ApiOperation(value="首页获取设备数据", notes="首页获取设备数据",produces = "application/json")
	public HashMap<String, Object> data(@RequestBody HomeDataRequestVo dataRequestVo)
	{		
		HomeDataResponseVo vo = new HomeDataResponseVo();
		List<Health> list = healthService.selectHealthNewList(dataRequestVo.getmCode());
		boolean flg = true;
		if(list!=null&&list.size()>0){
			Health health = list.get(0);
			vo.setBp(health.getDbp()+"/"+health.getSdp());
			vo.setHeartRate(String.valueOf(health.getHeartRate()));
			vo.setBpTime(health.getCreateTime());
			vo.setHeartRateTime(health.getCreateTime());
			if(health.getSdp().intValue()>150||health.getDbp().intValue()<60){//心率低于60，高于110，就为异常
				flg = false;
			}
			if(health.getHeartRate().intValue()<60||health.getHeartRate().intValue()>110){//血压  舒张压低于60  收缩压高于150就为异常
				flg = false;
			}
		}else{
			vo.setBp("0/0");
			vo.setHeartRate("0");
			vo.setBpTime(new Date());
			vo.setHeartRateTime(new Date());
		}
		vo.setHeartFlow("0");//暂无数据，固定
		vo.setHeartFlowTime(new Date());
		vo.setSpo("0");//暂无数据，固定
		vo.setSpoTime(new Date());
		if(flg){
			vo.setHealthStatus("1");//健康
		}else{
			vo.setHealthStatus("0");//不健康
		}
		

		Battery pa = new Battery();
		pa.setImei(dataRequestVo.getmCode());
		LinkedList<Battery> listB = batteryService.selectBatteryList(pa);
		if(listB!=null&&listB.size()>0){
			Battery ba = listB.get(0);
			vo.setBattery(String.valueOf(ba.getBattery()));
		}else{
			vo.setBattery("100");
		}
		/*Step sparm = new Step();
		sparm.setImei(dataRequestVo.getmCode());*/
		/*Step step = stepService.selectNewStep(sparm);
		if(step!=null){
			vo.setBattery(String.valueOf(step.getBattery()));
		}else{
			vo.setBattery("100");
		}*/
		return successApp(vo);
	}
	
	/**
	 * 一键测量
	 */
	@PostMapping("/measure")
	@ResponseBody
	@ApiOperation(value="一键测量", notes="一键测量",produces = "application/json")
	public HashMap<String, Object> measure(@RequestBody MachineBindRequestVo requestVo)
	{		
		try {
			JSONObject param = new JSONObject();
			param.put("imei", requestVo.getCode());
			System.out.println(param.toJSONString());
			String response = HttpUtils.sendPutJson("http://api.jiai.pro:8080/jiai/heartRates", param.toJSONString(),requestVo.getCode());
			System.out.println(response);
			JSONObject res = (JSONObject) JSONObject.parse(response);
			String errc = (String) res.get("code");
			if("0000".equals(errc)){
				String response1 = HttpUtils.sendPutJson("http://api.jiai.pro:8080/jiai/bloodPressure", param.toJSONString(),requestVo.getCode());
				System.out.println(response1);
				JSONObject res1 = (JSONObject) JSONObject.parse(response1);
				String errc1 = (String) res1.get("code");
				if("0000".equals(errc1)){
					return successApp("");
				}else{
					String message1 = (String) res1.get("message");
					return errorApp("hm-0002",message1);
				}
			}else{
				String message = (String) res.get("message");
				return errorApp("hm-0003",message);
			}
		} catch (Exception e) {
			return errorApp("hm-0001","测量失败");
		}
	}
	
	/**
	 * 一键测量结果
	 * @param dataRequestVo
	 * @return
	 */
	@PostMapping("/measureList")
	@ResponseBody
	@ApiOperation(value="一键测量结果", notes="一键测量结果",produces = "application/json")
	public HashMap<String, Object> measureList(@RequestBody HomeDataRequestVo dataRequestVo)
	{		
		HomeDataResponseVo vo = new HomeDataResponseVo();
		List<Health> list = healthService.selectFiveHealthList(dataRequestVo.getmCode());//选最新一个
		if(list!=null&&list.size()>0){
			Health health = list.get(0);
			vo.setBp(health.getDbp()+"/"+health.getSdp());
			vo.setHeartRate(String.valueOf(health.getHeartRate()));
			vo.setBpTime(health.getCreateTime());
			vo.setHeartRateTime(health.getCreateTime());
		}
		return successApp(vo);
	}
	
	/**
	 * SOS请求
	 */
	@PostMapping("/sos")
	@ResponseBody
	@ApiOperation(value="SOS请求", notes="SOS请求",produces = "application/json")
	public HashMap<String, Object> sos(HttpServletRequest request,@RequestBody MachineSOSRequestVo requestVo)
	{		
		try {
			User user = (User) request.getAttribute("user");
			Machine paramM = new Machine();
			paramM.setCode(requestVo.getCode());
			List<Machine> list = machineService.selectMachineList(paramM);
			if(list!=null&&list.size()>0){//设备已存在
				Machine ma = list.get(0);
				Location paramL = new Location();
				paramL.setImei(requestVo.getCode());
				String nickName = "";
				if(ma.getNickName()==null){
					nickName = ma.getPhone();
				}else{
					nickName = ma.getNickName();
				}
				if(ma.getSource().intValue()==1){//心电设备
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					String param = "registID=850DD4B27B9C445F84F0704CDB4D87BB&";
					param += "IMEI="+requestVo.getCode()+"&";
					param += "userName="+URLEncoder.encode(nickName, "UTF-8")+"&";
					param += "cellphone="+ma.getPhone()+"&";
					param += "lng="+requestVo.getLon()+"&";
					param += "lat="+requestVo.getLat()+"&";
					param += "upTime="+sdf.format(new Date())+"&";
					param += "homePhone1="+user.getPhone()+"";
					String response = HttpUtils.sendGet("http://60.194.110.52:9997/AnHome/AnPlusSos", param);
					System.out.println(response);
					JSONObject res = (JSONObject) JSONObject.parse(response);
					Integer errc = (Integer) res.get("state");
					if(errc==1){
						Sos sos = new Sos();
						sos.setImei(requestVo.getCode());
						sos.setLat(requestVo.getLat());
						sos.setLon(requestVo.getLon());
						sos.setCreateTime(new Date());
						sosService.insertSos(sos);
						return successApp("");
					}else{
						String message = (String) res.get("message");
						return errorApp("hm-0005",message);
					}
				}else{
					List<Location> locationList = locationService.selectLocationAllList(paramL);
					if(locationList!=null&&locationList.size()>0){
						Location l = locationList.get(0);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
						String param = "registID=850DD4B27B9C445F84F0704CDB4D87BB&";
						param += "IMEI="+requestVo.getCode()+"&";
						param += "userName="+URLEncoder.encode(nickName, "UTF-8")+"&";
						param += "cellphone="+ma.getPhone()+"&";
						param += "lng="+l.getLon()+"&";
						param += "lat="+l.getLat()+"&";
						param += "upTime="+sdf.format(new Date())+"&";
						param += "homePhone1="+user.getPhone()+"";
						String response = HttpUtils.sendGet("http://60.194.110.52:9997/AnHome/AnPlusSos", param);
						System.out.println(response);
						JSONObject res = (JSONObject) JSONObject.parse(response);
						Integer errc = (Integer) res.get("state");
						if(errc==1){
							Sos sos = new Sos();
							sos.setImei(requestVo.getCode());
							sos.setLat(l.getLat());
							sos.setLon(l.getLon());
							sos.setCreateTime(new Date());
							sosService.insertSos(sos);
							return successApp("");
						}else{
							String message = (String) res.get("message");
							return errorApp("hm-0005",message);
						}
					}else{
						return errorApp("hm-0004","SOS失败-缺少定位信息");
					}
				}
			}else{
				return errorApp("hm-0004","SOS失败-设备不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return errorApp("hm-0004","SOS失败");
		}
	}
}
